<template>
    <div class="upload-container" @click="uploadClick">
        <img v-if="path" :src="path" alt="">
        <div v-if="!path" class="upload-before" >
            <i class="icon iconfont icon-addv"></i>
            <p>{{ label }}</p>
        </div>
        <!-- capture="camera" -->
        <input type="file" v-show="false" @change="uploadChange" accept="image/*" ref="fileinput">

        <div v-if="progress" class="weui-loading_toast custom-classname">
            <div class="weui-mask_transparent"></div> 
            <div class="weui-toast weui-animate-fade-in"> 
                <i class="weui-loading weui-icon_toast"></i> 
                <p class="weui-toast__content">{{ progress }}</p> 
            </div> 
        </div>
    </div>
</template>

<script>
export default {
    name: 'uploadImg',
    props: ['url', 'label'],
    data() {
        return {
            path: null,
            progress: 0,
        }
    },
    created() {
        this.path = this.url
    },
    methods: {
        // 点击上传
        uploadClick(e) {
            if(this.progress !== 0) return false
            if (e.target !== this.$refs.fileinput) {
                e.preventDefault()
                if (document.activeElement !== this.$refs) {
                    this.$refs.fileinput.click()
                }
            }
        },
        uploadChange(e) {
            if(this.progress !== 0) return false
            e.preventDefault()
            const blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice
            if (!blobSlice || typeof FileReader === 'undefined') {
                weui.alert('上传组件不被此浏览器支持');
                return false
            }
            const files = e.target.files || e.dataTransfer.files
            if (files.length < 0) {
                weui.alert('请选择文件')
                return false
            }
            const file = files[0]
            let _this = this
            if(/image\/\w+/.test(file.type)){  //文件类型只能是图片
                var fr = new FileReader()
                fr.onloadend = function(evt) {
                    _this.path = evt.target.result
                }
                fr.readAsDataURL(file)

                this.imgResize(file, function(file) {
                    _this.upload(file)
                })

            }else{
                weui.alert("请选择图片文件")
            }
        },
        imgResize(file, callback){
            let _this = this
            var fileReader = new FileReader();
            fileReader.onload = function() {
                var IMG = new Image();
                IMG.src = this.result;
                IMG.onload = function(){
                    var w = this.naturalWidth, h = this.naturalHeight, resizeW = 0, resizeH = 0;
                    // maxSize 是压缩的设置，设置图片的最大宽度和最大高度，等比缩放，level是报错的质量，数值越小质量越低
                    var maxSize = {
                        width: 1080,
                        height: 1080,
                        level: 0.8
                    };
                    if(w > maxSize.width || h > maxSize.height){
                        var multiple = Math.max(w / maxSize.width, h / maxSize.height);
                        resizeW = w / multiple;
                        resizeH = h / multiple;
                    } else {
                        // 如果图片尺寸小于最大限制，则不压缩直接上传
                        return callback(file)
                    }
                    var canvas = document.createElement('canvas'),
                    ctx = canvas.getContext('2d');
                    if(window.navigator.userAgent.indexOf('iPhone') > 0 && 0){
                        canvas.width = resizeH;
                        canvas.height = resizeW;
                        ctx.rotate(90 * Math.PI / 180);
                        ctx.drawImage(IMG, 0, -resizeH, resizeW, resizeH);
                    }else{
                        canvas.width = resizeW;
                        canvas.height = resizeH;
                        ctx.drawImage(IMG, 0, 0, resizeW, resizeH);
                    }
                    var base64 = canvas.toDataURL('image/jpeg', maxSize.level);
                    _this.convertBlob(window.atob(base64.split(',')[1]), callback);
                }
            };
            fileReader.readAsDataURL(file);
        },
        convertBlob(base64, callback){
            var buffer = new ArrayBuffer(base64.length);
            var ubuffer = new Uint8Array(buffer);
            for (var i = 0; i < base64.length; i++) {
                ubuffer[i] = base64.charCodeAt(i)
            }
            var blob;
            try {
                blob = new Blob([buffer], {type: 'image/jpg'});
            } catch (e) {
                window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
                if(e.name === 'TypeError' && window.BlobBuilder){
                    var blobBuilder = new BlobBuilder();
                    blobBuilder.append(buffer);
                    blob = blobBuilder.getBlob('image/jpg');
                }
            }
            callback(blob)
            // canvas.toBlob(function(blob) {
            //     console.log(blob)
            // }, 'image/jpeg', 0.95);
        },
        upload(fileResize) {
            this.progress = 0
            let data = new FormData();
            data.append('file', fileResize);
            var config = {
                headers: {'Content-Types': 'multipart/form-data'},
                onUploadProgress: progressEvent => {
                    this.progress = (progressEvent.loaded / progressEvent.total * 100 | 0) + '%'
                }
            };
            axios.post('/public/upload', data, config).then( res => {
                let resData = res.data;
                if (resData.status === 'success') {
                    this.$emit('getPath', resData.data.path);
                } else {
                    weui.alert(res.data.message)
                }
                this.progress = 0
            }).catch(e => {
                this.progress = 0
                console.log(e)
            })
        }
    }
}
</script>

<style lang="scss" scoped>
    .upload-container {
        display: flex;
        width: 8rem;
        height: 4rem;
        border: 1px dashed #CCCCCC;
        align-items: center;
        justify-content: center;
        line-height: 1;
        font-size: .373333rem;
        color: #999;
        .upload-before {
            text-align: center;
        }
        .icon {
            display: inline-block;
            font-size: 1rem;
            color: #999;
            margin-bottom: .18rem;
        }
        img {
            width: 100%;
            height: 100%;
        }
    }
</style>

